package com.party.core.service.counterfoil.biz;

import com.google.common.collect.Lists;
import com.party.common.constant.Constant;
import com.party.common.utils.StringUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.activity.Activity;
import com.party.core.model.counterfoil.Counterfoil;
import com.party.core.model.counterfoil.CounterfoilBusiness;
import com.party.core.model.member.MemberAct;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.counterfoil.ICounterfoilBusinessService;
import com.party.core.service.counterfoil.ICounterfoilService;
import com.party.core.service.goods.IGoodsCouponsService;
import com.party.core.service.member.IMemberActService;
import com.party.core.utils.MyBeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Transformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;
import java.util.function.Consumer;

@Service
public class CounterfoilBizService {
	@Autowired
	private ICounterfoilService counterfoilService;
	@Autowired
	private IActivityService activityService;
	@Autowired
	private IMemberActService memberActService;
	@Autowired
	private ICounterfoilBusinessService counterfoilBusinessService;
	@Autowired
    private IGoodsCouponsService goodsCouponsService;

	Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 保存票据业务
     *
     * @param counterfoils
     * @param businessId
     * @param businessType
     * @param memberId
     */
    public List<Counterfoil> saveBiz(List<Counterfoil> counterfoils, String businessId, String businessType,
                                     String memberId) {
        List<Counterfoil> newCounterfoils2 = Lists.newArrayList();
        if (counterfoils != null) {
            for (Counterfoil counterfoil : counterfoils) {
                try {
                    if (StringUtils.isNotEmpty(counterfoil.getId())) {
                        // delFlag为1表示删除
                        if (StringUtils.isNotEmpty(counterfoil.getDelFlag()) && counterfoil.getDelFlag().equals(BaseModel.DEL_FLAG_DELETE)) {
                            Counterfoil db = counterfoilService.get(counterfoil.getId());
                            if (db.getJoinNum() > 0) {
                                throw new Exception("该票据已有人报名，不能删除");
                            }
							/*List<CounterfoilBusiness> businesses = counterfoilBusinessService.findByCounterfoilId(counterfoil.getId());
							for (CounterfoilBusiness counterfoilBusiness : businesses) {
								counterfoilBusinessService.delete(counterfoilBusiness.getId());
							}*/
                            counterfoilService.deleteLogic(counterfoil.getId());
                        } else {
                            Counterfoil t = counterfoilService.get(counterfoil.getId());
                            MyBeanUtils.copyBeanNotNull2Bean(counterfoil, t);
                            counterfoilService.update(t);
                            newCounterfoils2.add(t);
                        }
                    } else {
                        Counterfoil cc = saveCounterfoil(businessId, businessType, counterfoil, memberId);
                        newCounterfoils2.add(cc);
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                    continue;
                }
            }

            List<Counterfoil> newCounterfoils = counterfoilService.list(new Counterfoil(businessId, businessType));
            if (newCounterfoils.size() == 0 || newCounterfoils.size() > 0) {
                Counterfoil counterfoil = newCounterfoils.get(0);
                if (businessType.equals(Constant.BUSINESS_TYPE_ACTIVITY)
                        || businessType.equals(Constant.BUSINESS_TYPE_COURSE)) {
                    Activity activity = activityService.get(businessId);
                    activity.setPrice(counterfoil.getPayment());
                    activity.setLimitNum(counterfoil.getLimitNum());
                    activity.setJoinNum(counterfoil.getJoinNum());
                    activityService.update(activity);
                }
            }
        }
        Collections.sort(newCounterfoils2, (o1, o2) -> {
            if (o1.getSort() < o2.getSort()) {
                return -1;
            } else {
                return 1;
            }
        });
        return newCounterfoils2;
    }

	/**
	 * 保存票据
	 *
	 * @param businessId
	 * @param businessType
	 * @param t
	 * @param memberId
	 */
	public Counterfoil saveCounterfoil(String businessId, String businessType, Counterfoil t, String memberId) {
		Counterfoil counterfoil = new Counterfoil();
		counterfoil.setCreateBy(memberId);
		counterfoil.setUpdateBy(memberId);
		counterfoil.setPayment(t.getPayment());
		counterfoil.setLimitNum(t.getLimitNum());
		counterfoil.setBusinessId(businessId);
		counterfoil.setMaxBuyNum(t.getMaxBuyNum());
		counterfoil.setBusinessType(businessType);
		counterfoil.setJoinNum(t.getJoinNum() == null ? 0 : t.getJoinNum());
		counterfoil.setSort(t.getSort() == null ? 0 : t.getSort());
		counterfoil.setName(t.getName());
		counterfoil.setType(t.getType());
		counterfoil.setRemarks(t.getRemarks());
		counterfoilService.insert(counterfoil);
		return counterfoil;
	}

	/**
	 * 显示的票价
	 *
	 * @param counterfoils
	 * @param actId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String getShowPrice(List<Counterfoil> counterfoils, String actId) {
		if (counterfoils == null) {
			Counterfoil t = new Counterfoil();
			t.setBusinessId(actId);
			counterfoils = counterfoilService.list(t);
		}
		if (counterfoils.size() > 0) {
			List<Float> prices = (List<Float>) CollectionUtils.collect(counterfoils, new Transformer() {

				@Override
				public Object transform(Object input) {
					Counterfoil mm = (Counterfoil) input;
					return mm.getPayment();
				}
			});
			Float min = Collections.min(prices); // 最小票价
			Float max = Collections.max(prices); // 最大票价
			if (min.equals(max)) {
                if (min.equals(Float.valueOf("0.0"))) {
                    return "0";
                }
                return min.toString();
			} else {
                if (min.equals(Float.valueOf("0.0"))) {
                    return "0" + "~" + max.toString();
                }
                return min.toString() + "~" + max.toString();
			}
		}
		return "";
	}

	/**
	 * 获取活动的票据，同时更新相关数据joinNum limitNum
	 *
	 * @param activityId
	 * @return
	 */
	public List<Counterfoil> getActivityCounterfoils(String activityId) {
		Counterfoil t = new Counterfoil();
		t.setBusinessId(activityId);
        List<Counterfoil> newCounterfoils = Lists.newArrayList();
		List<Counterfoil> counterfoils = counterfoilService.list(t);
		if (counterfoils.size() > 0) {
			Integer joinNum = 0;
			Integer limitNum = 0;
			Activity activity = activityService.get(activityId);
			for (Counterfoil counterfoil : counterfoils) {
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("actId", activityId);
				params.put("counterfoilId", counterfoil.getId());
				Integer join = memberActService.getSuccessMemberAct(params);
				Counterfoil dbCounterfoil = counterfoilService.get(counterfoil.getId());
				if (dbCounterfoil.getJoinNum() == null || !dbCounterfoil.getJoinNum().equals(join)) {
					dbCounterfoil.setJoinNum(join);
					counterfoilService.update(dbCounterfoil);
				}
                newCounterfoils.add(dbCounterfoil);
				joinNum += join; // 报名数
			}

			for (Counterfoil counterfoil : counterfoils) {
				if (counterfoil.getLimitNum().equals(new Integer(0))) {
					limitNum = 0;
					break;
				}
				limitNum += counterfoil.getLimitNum();
			}

			boolean flag = false;
			// 购买人数
			if (activity.getJoinNum() == null) {
				activity.setJoinNum(0);
				flag = true;
			} else if (!joinNum.equals(activity.getJoinNum())) {
				activity.setJoinNum(joinNum);
				flag = true;
			}
			// 限制人数
			if (activity.getLimitNum() == null) {
				activity.setLimitNum(0);
				flag = true;
			} else if (!activity.getLimitNum().equals(limitNum)) {
				activity.setLimitNum(limitNum);
				flag = true;
			}
			if (flag) {
				activityService.update(activity);
			}
		}
		return newCounterfoils;
	}

    /**
     * 删除票券
     *
     * @param businessId   业务id
     * @param businessType 业务类型
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean deleteCounterfoilBiz(String businessId, String businessType) {
		try {
			List<Counterfoil> counterfoilList = counterfoilService.findByBusinessId(businessId, businessType);
			counterfoilList.forEach(new Consumer<Counterfoil>() {
				@Override
				public void accept(Counterfoil counterfoil) {
					List<CounterfoilBusiness> businesses = counterfoilBusinessService.findByCounterfoilId(counterfoil.getId());
					businesses.forEach(new Consumer<CounterfoilBusiness>() {
						@Override
						public void accept(CounterfoilBusiness counterfoilBusiness) {
							if (Constant.BUSINESS_TYPE_ACTIVITY.equals(businessType)) {
								MemberAct memberAct = memberActService.get(counterfoilBusiness.getBusinessId());
								if (memberAct != null) {
									goodsCouponsService.deleteByOrderId(memberAct.getOrderId());
									memberActService.delete(memberAct.getId());
								}
								counterfoilBusinessService.delete(counterfoilBusiness.getId());
							}
						}
					});
					counterfoilService.delete(counterfoil.getId());
				}
			});
			return true;
		} catch (Exception e) {
			logger.error("删除票券异常", e);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return false;
		}
	}
}
